/* eslint-disable no-unused-vars */
import './img/1.jpeg';
import './img/2.jpeg';
import './img/3.jpeg';

let l1 = new Light('.box1');
l1.init();

//自动播放，鼠标移入就不能播放
let l2 = new Light('.box2');
l2.init();
l2.AutoPlay();

//自动播放，下到上播放
let l3 = new Light('.box3');
l3.init();
l3.Play();
//定义红绿灯类
function Light($box) {
    //装红绿灯的容器
    this.box = document.querySelector($box);
    //初始值
    this.index = 1;
}

//初始化图片
Light.prototype.init = function () {
    //创建图片标签
    this.img = new Image();
    this.img.src = `./img/${this.index}.jpeg`;
    //将图片添加到容器中
    this.box.appendChild(this.img);
    //初始化完成之后绑定点击事件
    this.bindClick();
    //设置图片不可拖拽
    // this.img.draggable = false;
    this.flag = true;
};

//绑定事件
Light.prototype.bindClick = function (flag) {
    this.img.addEventListener('click', () => {
        if (this.flag) {
            this.index++;
            if (this.index > 3) {
                this.index = 1;
            }
            this.img.src = `./img/${this.index}.jpeg`;
        }
    });
    this.box.addEventListener('dragstart', (event) => {
        event.preventDefault();
    });
};

//box2自动播放
Light.prototype.AutoPlay = function () {
    this.flag = false;
    this.timer = null;
    this.timer = setInterval(() => {
        this.index++;
        if (this.index > 3) {
            this.index = 1;
        }
        this.box.children[0].src = `./img/${this.index}.jpeg`;
        // console.log(this.box.children[0]);
    }, 1000);
    this.box.addEventListener('mouseenter', () => {
        clearInterval(this.timer);
    });
    this.box.addEventListener('mouseleave', () => {
        this.timer = setInterval(() => {
            this.index++;
            if (this.index > 3) {
                this.index = 1;
            }
            this.box.children[0].src = `./img/${this.index}.jpeg`;
        }, 1000);
    });
};
//box3由1-3播放再到3-1播放
Light.prototype.Play = function () {
    this.timer = null;
    this.flag = false;
    if (this.index == 1) {
        this.timer = setInterval(() => {
            this.index++;
            this.box.children[0].src = `./img/${this.index}.jpeg`;
            if (this.index == 3) {
                clearInterval(this.timer);
                this.timer = setInterval(() => {
                    this.index--;
                    this.box.children[0].src = `./img/${this.index}.jpeg`;
                    if (this.index == 1) {
                        clearInterval(this.timer);
                        this.Play();
                    }
                }, 2000);
            }
        }, 2000);
    }
};
